<?php

namespace App\Http\Proxy;

use Cookie;
use GuzzleHttp\Client;

class TokenProxy
{

    protected $http;

    public function __construct(Client $http)
    {
        $this->http = $http;

    }

    public function login($email, $password)
    {
        if (auth()->attempt(['email' => $email, 'password' => $password, 'is_active' => 1])) {
            return $this->proxy('password', [
                'username' => $email,
                'password' => $password,
                'scope' => '',
            ]);
        }
        return response()->json([
            'status' => false,
            'message' => 'Credentials not match or this user not active',
        ], 421);

    }

    public function logout()
    {
        $user = auth()->guard('api')->user();

        if (!is_null($user)) {
            $accessToken = $user->token();
            app('db')->table('oauth_refresh_tokens')
                ->where('access_token_id', $accessToken->id)
                ->update(['revoked' => true]);

            $accessToken->revoke();
        }

        app('cookie')->queue(app('cookie')->forget('refreshToken'));

        return response()->json([
            'status' => true,
            'message' => 'User logouted',
        ]);
    }

    public function refresh()
    {
        $refreshToken = request()->cookie('refreshToken');
        return $this->proxy('refresh_token', [
            'refresh_token' => $refreshToken,
        ]);
    }
    public function proxy($grantType, array $data)
    {
        $data = array_merge($data, [
            'client_id' => config('services.passport.client_id'),
            'client_secret' => config('services.passport.client_secret'),
            'grant_type' => $grantType,
        ]);

        $response = $this->http->post(route('passport.token'), [
            'form_params' => $data,
        ]);

        $token = json_decode((string) $response->getBody(), true);

        $data = [
            'token' => $token['access_token'],
            'auth_id' => md5($token['access_token']),
            'expires_in' => $token['expires_in'],
        ];

        $refreshCookie = cookie('refreshToken', $token['refresh_token'],
        (int) config('app.token.refresh_in'), null, null, false, true);

        return response()->json($data)->cookie($refreshCookie);
    }
}
